using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ACM.cmsarea08.Controls
{

    [ToolboxData("<{0}:AjaxFileupload runat=server></{0}:AjaxFileupload>")]
    public partial class AjaxFileupload : CompositeControl
    {
        private string myID
        {
            get
            {
                return "AjaxFileupload_" + ID;
            }
        }
        private string IDUnico
        {
            get
            {
                string _key = myID + "_myKey";

                if (!string.IsNullOrEmpty(Request.QueryString[myID]))
                    return Request.QueryString[myID];
                else if (null != ViewState[_key])
                    return ViewState[_key].ToString();

                return string.Empty;
            }
            set
            {
                string _key = myID + "_myKey";
                ViewState.Add(_key, value);
            }
        }
        private string myID1
        {
            get { return myID + "1"; }
        }
        private Azioni myIDAzione
        {
            get{
                if (!string.IsNullOrEmpty(Request.QueryString[myID1]))
                {
                    string _aux = Request.QueryString[myID1];
                    int _iAux = Convert.ToInt32(_aux);
                    return (Azioni) _iAux;
                }
                return Azioni.Inizio;
            }
        }

        private string myID2
        {
            get { return myID + "2"; }
        }
        private string myID2Valore
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString[myID2]))
                    return Request.QueryString[myID2];
                return string.Empty;
            }
        }

        private string myID3
        {
            get { return myID + "3"; }
        }
        private string myID3Valore
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString[myID3]))
                    return Request.QueryString[myID3];
                return string.Empty;
            }
        }
        private string azione
        {
            get { return Request.Url.AbsoluteUri; }
        }


        public new string CssClass
        {
            get
            {
                if (null != ViewState[myID + "CssClass"])
                    return ViewState[myID + "CssClass"].ToString();
                return string.Empty;
            }
            set
            {
                ViewState[myID + "CssClass"] = value;
            }
        }
        public new string Style
        {
            get
            {
                if (null != ViewState[myID + "Style"])
                    return ViewState[myID + "Style"].ToString();
                return string.Empty;
            }
            set { ViewState[myID + "Style"] = value; }
        }
        [Browsable(false),
         Description("FileUploaderAJAX is posting a file")]
        public bool IsPosting
        {
            get { return IsRequesting && myIDAzione.Equals(Azioni.Uploading) && (Request.Files.Count > 0); }
        }
        [Browsable(false),
         Description("FileUploaderAJAX is requesting")]
        public bool IsRequesting
        {
            get { return !string.IsNullOrEmpty(Request.QueryString[myID1]); }
        }

        private HttpPostedFileAJAX _PostedFile = null;
        [Browsable(false),
         Description("The file which is being posted")]
        public HttpPostedFileAJAX PostedFile
        {
            get
            {
                if ((_PostedFile == null) && (IsPosting))
                {
                    HttpPostedFile file = Request.Files[0];
                    _PostedFile = new HttpPostedFileAJAX(file.FileName, file.ContentType, file.ContentLength);
                }

                return _PostedFile;
            }
            private set { _PostedFile = value; }
        }
        private List<HttpPostedFileAJAX> _history = null;

        [Browsable(false),
         Description("The uploaded files history")]
        public List<HttpPostedFileAJAX> History
        {
            get
            {
                if ((null == _history) && (null != Session[IDUnico]))
                    _history = (List<HttpPostedFileAJAX>)Session[IDUnico];

                return _history;
            }
            private set { Session[IDUnico] = value; }
        }

        public AjaxFileupload() { }



        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (string.IsNullOrEmpty(IDUnico))
                IDUnico = "AFUP_" + Guid.NewGuid().ToString().Replace("-", "_");

            if (!DesignMode && !Page.IsPostBack)
            {
                switch (myIDAzione)
                {
                    case Azioni.Normale:
                        normale(); break;
                    case Azioni.Uploading:
                        uploaded(); break;
                    case Azioni.Eliminazione:
                        elimina(); break;
                    case Azioni.Recupero:
                        recupero(); break;
                }
            }

        }

        private void normale()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(preIframe(true));
            sb.AppendFormat(
                @"
                <div id=""AFUPD_myIframe"">
                <input id=""file"" type=""file"" name=""image"" onchange=""{4}upload()"" /> 
                 <a href=""javascript:void(0)"" onclick=""{2}ocultarDiv('{0}')"">{3}</a>       
                </div>            
                <div id=""FUA_uploading"">
                <span id=""FUA_uploading_span"">{1}</span>
                </div>

            ",
                myID2Valore,
                "Sto Caricando...",
                myID,
                "NASCONDI",
                myID1);


            sb.AppendFormat(
                @"<script language=""javascript"" type=""text/javascript"">

                {0}show(0);


                function {0}upload()
                {{          
                    {0}show(1);

                    var action = '{6}';
                    var separador = action.lastIndexOf('?');
                    action = action.substring(0, separador + 1);
                    action += '{0}={3}&{1}={2}&{4}={5}';
                    alert('da dentro:\n ' + action);
                    document.forms[0].action = action;
	                setTimeout('document.iform.submit()',100);
                }}

                function {0}show(N)
                {{
                    var alldivs = document.getElementsByTagName('div')
                    for (i = 0; i < alldivs.length; i++)
                    {{
                        if (i!=N)
                        {{
                            alldivs[i].style.display = 'none';
                        }}
                        else
                        {{
                            alldivs[i].style.display = '';
                        }}
                    }}
                }}

                {7}           

                </script>"
                , myID1, myID2, myID2Valore, (int)Azioni.Uploading, myID, IDUnico, azione,
                nascondiDiv());
            sb.Append(postIframe(true));
            mostraHTML(sb.ToString());
        }
        private void uploaded()
        {
            if (IsPosting)
            {
                mostraHTML(uploadedAux(PostedFile));
            }
        }
        private void elimina()
        {
            mostraHTML(RemoveAux(0));
        }
        private void recupero()
        {
            /*
            int historialIndex = FindHistorialIndex(clave3Value);
            HttpPostedFileAJAX _MyPostedFile = History[historialIndex];

            if (_MyPostedFile.Deleted)
                mostrarHTML(RemoveAux(historialIndex));
            else
                mostrarHTML(uploadedAux(_MyPostedFile));
             */
        }

        protected override void Render(HtmlTextWriter writer)
        {
            //base.Render(writer);
            if (DesignMode)
            {
                writer.Write("<input type=\"file\" />");
                return;
            }
            string ritorno = string.Empty;
            ritorno = init_layour();
            writer.WriteLine("<!-- Ajax file uploader by ciccio -->");
            writer.WriteLine(Utility.prepareJS(ritorno,false));
            writer.WriteLine("<!-- fine Ajax file uploader by ciccio -->");
            writer.WriteLine();
        }

        private string init_layour()
        {
            getJavascript();
            return creaDivs();
        }
        private string creaDivs()
        {
            //            <a href=""javascript:void(0)"" onclick=""{0}add('{2}', '{3}')"" id=""{0}Add"">{1}</a>
            string postedFile = "";
                postedFile = string.Format(
                @"<div id=""{0}_container""><img src=""#"" alt=""nofile""/> - 
                  <a href=""javascript:void(0)"" id=""{0}Add"">download</a>  -
                  <a href=""javascript:void(0)"" id=""{0}Add"">clear</a></div>",
                                                                         myID);
 
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<div{0}>", !string.IsNullOrEmpty(CssClass) ? " class=\"" + CssClass + "\"" : string.Empty);
            sb.AppendFormat(
                @"         
            <div id=""{0}"" style=""padding:0px; margin:0px;"">
                <!--<a href=""http://fileuploadajax.subgurim.net"">FileUpload AJAX ASP.NET</a> Powered By Subgurim-->
            </div>   
            {1}
            </div>",
                myID,postedFile ); //"AGGIUNGI", (int)Azioni.Normale, (int)Azioni.Recupero);


             

            return sb.ToString();
        }
        private void getJavascript()
        {
            
            ClientScriptProxy cs = ClientScriptProxy.Current;
            cs.RegisterStartupScript(Page,
                                      Page.GetType(),
                                      myID,
                                      caricaJS(),
                                      true);
             
        }

        private string caricaJS()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(js_core());

            if (Page.IsPostBack)
                sb.AppendFormat("setTimeout('caricaAUPD_{0}()', 200);", myID);
            else
                sb.Append(inizializzajs());

            return sb.ToString();
        }

        private string js_core()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat(
                @" 
	                var i = 1;

                function caricaAUPD_{0}()
                {{
                    {0}add('{1}', '{2}');
                    ",
                myID, (int)Azioni.Normale, (int)Azioni.Recupero);


//qui inserisco mostra files se presenti

            sb.AppendFormat(
                @"
            }}

	        function {3}add(clave1Value, clave3Value)
	        {{
	            i++;
	            var SFUA_id = '{4}SFUA' + i;
                var SFUA_Div_Id = '{4}SFUA_Div' + i; 
                var myDiv = document.createElement('div');	
                myDiv.id = SFUA_Div_Id;
                myDiv.style.margin = '0px';
                myDiv.style.padding = '0px';
	            var new_iframe = document.createElement('iframe');
	            new_iframe.frameBorder = '0';
	            new_iframe.height = '22px';
	            new_iframe.width = '100%';
	            new_iframe.scrolling = 'no';
	            new_iframe.id = SFUA_id;
	            new_iframe.name = SFUA_id;
	            new_iframe.marginwidth = '0px';
	            new_iframe.marginheight = '0px';
	            new_iframe.hspace = '0px';
	            new_iframe.vspace = '0px';
	            var padre = document.getElementById('{3}');
                myDiv.appendChild(new_iframe);
	            padre.appendChild(myDiv);

                var _href = window.location.href;
                var _sharp = _href.lastIndexOf('#');
                if (_sharp>-1)
                {{
                    _href = _href.substring(0, _sharp);
                }}

                var infoQuery = '{0}='+clave1Value+'&{1}='+SFUA_Div_Id+'&{3}={4}&{6}='+clave3Value;
                var separador = (window.location.search=='') ? '?' : '&';
                var action = _href + separador + infoQuery;
                alert('contenitore: ' +action);
                document.getElementById(SFUA_id).src = action;
                {3}postAdd();

	        }}

            {2}
            function {3}postAdd()
            {{
                {3}assureMaxFilesLimit();
            }}



            ",
                myID1, myID2, "", myID, IDUnico, azione, myID3,
                (int)Azioni.Recupero);
            //AssureMaxFilesLimit(false, false)

            return sb.ToString();
        }
        private string inizializzajs()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat(
                @"
                function addEvent(elm, evType, fn, useCapture) 
                {{
                    if (elm.addEventListener) 
                    {{
                        elm.addEventListener(evType, fn, useCapture);
                        return true;
                    }}
                    else if (elm.attachEvent) 
                    {{
                        var r = elm.attachEvent('on' + evType, fn);
                        return r;
                    }}
                    else 
                    {{
                        elm['on' + evType] = fn;
                    }}
                }} 
                addEvent(window,'load',caricaAUPD_{0}, false);
                    ",
                myID);

            return sb.ToString();

        }

        private string preIframe(bool conForm)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("<html>");
            sb.Append("<head>");

            sb.Append("<style>");
            sb.Append("body{margin: 0;padding: 0;}");
            sb.Append(Style);
            sb.Append("</style>");

            sb.Append("</head>");
            sb.Append("<body>");

            if (conForm)
                sb.Append("<form name=\"iform\" method=\"post\" enctype=\"multipart/form-data\">");
            return sb.ToString();
        }
        private string postIframe(bool conForm)
        {
            StringBuilder sb = new StringBuilder();

            if (conForm)
                sb.Append("</form>");
            sb.Append("</body>");
            sb.Append("</html>");

            return sb.ToString();
        }
        private string nascondiDiv()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat(
                @"
            function {0}ocultarDiv(SFUA_Div_Id, forceShowAdd)
            {{
                var par = window.parent.document;
                var myDiv = par.getElementById(SFUA_Div_Id);
                myDiv.style.display = 'none';

                var _Add = par.getElementById('{0}Add');
                _Add.style.display = '';

                return true;
            }}
        ",
                myID);

            return sb.ToString();
        }
        private void mostraHTML(string html)
        {
            Response.Clear();
            Response.ContentType = "text/html";
            Response.Write(html);
            Response.End();
        }


        public enum Azioni
        {
            Uploading,
            Normale,
            Inizio,
            Recupero,
            Eliminazione
        }

        private HttpRequest Request
        {
            get { return HttpContext.Current.Request; }
        }
        private HttpResponse Response
        {
            get { return HttpContext.Current.Response; }
        }
        private HttpSessionState Session
        {
            get { return HttpContext.Current.Session; }
        }
        private HttpServerUtility Server
        {
            get { return HttpContext.Current.Server; }
        }


        private string uploadedAux(HttpPostedFileAJAX _MyPostedFile)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(preIframe(true));

            sb.Append(_MyPostedFile.responseMessage_Uploaded);
            HttpPostedFile file = Request.Files[0];
            if (_MyPostedFile.ContentLength > 0 && file!=null)
            {
                if (History == null)
                    History = new List<HttpPostedFileAJAX>();
                if (History.Count == 0)
                    History.Add(_MyPostedFile);
                else
                    History[0] = _MyPostedFile;

                _MyPostedFile.Saved = true;
            }


            if (_MyPostedFile.Saved)
            {
                sb.AppendFormat(" <a href=\"javascript:void(0)\" onclick=\"{1}delete('{0}')\">{2}</a>",
                                _MyPostedFile.FileName_SavedAs, myID, "ELIMINA");
                sb.AppendFormat(" <input type=\"hidden\" id=\"{0}\">", myID);
            }
            else
            {
                sb.AppendFormat(" <a href=\"javascript:void(0)\" onclick=\"{2}ocultarDiv('{0}')\">{3}</a>", myID2Valore,
                                myID1, myID, "[X]");
            }

            sb.AppendFormat(
                @"
                    <script language=""javascript"">

                    var FileName = '{12}';
                    var FileName_SavedAs = '{13}';
                    var FileName_Path = '{22}';
                    var ContentType = '{14}';
                    var ContentLength = {15};
                    var responseMessage_Uploaded = '{16}';
                    var responseMessage_Uploaded_Saved = '{17}';
                    var responseMessage_Uploaded_NotSaved = '{18}';
                    var Saved = {19};
                    var Deleted = {20};
                    var Type = '{21}';

                    {11}

                    function {6}delete()
                    {{   
                        {10}

                        var action = '{8}';
                        var separador = action.lastIndexOf('?');
                        action = action.substring(0, separador + 1);
                        action += '{0}={3}&{1}={4}&{2}={5}&{6}={7}';

                        document.forms[0].action = action;
	                    setTimeout('document.iform.submit()',1);
                    }}

                    {9}

                    </script>"
                , myID1, myID2, myID3, (int)Azioni.Eliminazione, myID2Valore, _MyPostedFile.FileName_SavedAs,
                myID, IDUnico, azione, nascondiDiv()
                , "", ""
                , _MyPostedFile.FileName
                , _MyPostedFile.FileName_SavedAs
                , _MyPostedFile.ContentType
                , _MyPostedFile.ContentLength
                , HttpUtility.HtmlEncode(Utility.prepareJS(_MyPostedFile.responseMessage_Uploaded))
                , HttpUtility.HtmlEncode(Utility.prepareJS(_MyPostedFile.responseMessage_Uploaded_NotSaved))
                , HttpUtility.HtmlEncode(Utility.prepareJS(_MyPostedFile.responseMessage_Uploaded_Saved))
                , _MyPostedFile.Saved.ToString().ToLower()
                , _MyPostedFile.Deleted.ToString().ToLower()
                , _MyPostedFile.Type.ToString(),
                _MyPostedFile.FileName_Path);

            sb.Append(postIframe(true));

            return sb.ToString();
        }
        private string RemoveAux(int historyIndex)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(preIframe(true));


            sb.Append("<span style=\"text-decoration: line-through;\">");
            string mensaje = History[historyIndex].responseMessage_Uploaded;

            string pattern_entreTags = "<[^<>]*>";
            mensaje = Regex.Replace(mensaje, pattern_entreTags, string.Empty);


            sb.Append(mensaje);
            sb.Append("</span>");
            sb.AppendFormat(" <a href=\"javascript:void(0)\" onclick=\"{2}ocultarDiv('{0}')\">{3}</a>", myID2Valore,
                            myID1, myID, "[X]");

            sb.AppendFormat(
                @"
                    <script language=""javascript"">
                    {1}

                    {0}
                    </script>"
                , nascondiDiv(), "");

            return sb.ToString();
        }    
    }
}
